import tui from './httpRequest';
/**
 * @description: 路由跳转
 * @param {*} index 判断执行什么操作 1：返回 2：去普通页 3：去tab页面 4：跳转到指定页面，关闭其他页面
 * @param {*} url 目标跳转页面
 */
export function goPath(index, url) {
    if (index == 1) {
        // 返回上级页面
        uni.navigateBack({
            delta: url,
            animationType: "pop-out",
            animationDuration: 300,
        });
    } else if (index == 2) {
        // 页面跳转
        uni.navigateTo({
            url: url,
            animationType: "pop-in",
            animationDuration: 300,
        });
    } else if (index == 3) {
        // 跳转tab页面
        uni.switchTab({
            url: url,
            animationType: "pop-in",
            animationDuration: 300,
        });
    } else if (index == 4) {
        // 关闭所有页面跳转
        uni.reLaunch({
            url: url,
            animationType: "pop-in",
            animationDuration: 300,
        });
    } else if (index == 5) {
        uni.redirectTo({
            url: url,
            animationType: "pop-in",
            animationDuration: 300,
        });
    }
}
/**
 * 防抖函数
 * @param {*} fn 要执行的函数
 * @param {*} time 延迟执行的毫秒数 默认200毫秒
 */

export function debounce(fn, delay) {
    var delay = delay || 200;
    var timer = null;
    return function () {
        var args = arguments;
        var that = this;
        if (timer) {
            console.log("sss");
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(that, args);
        }, delay);
    };
}


/**
 * 显示消息
 * @param {*} title 显示的内容
 * @param {*} duration 显示时间，默认1.5s
 * @param {*} icon 显示图标，默认没有
 */
export function modal(title, content, showCancel, callback, confirmColor, confirmText) {
    uni.showModal({
        title: title || '提示',
        content: content,
        showCancel: showCancel,
        cancelColor: "#555",
        confirmColor: confirmColor || "#5677fc",
        confirmText: confirmText || "确定",
        success(res) {
            if (res.confirm) {
                callback && callback(true)
            } else {
                callback && callback(false)
            }
        }
    })
}

/**
 * 显示轻消息
 * @param {*} title 显示的内容
 * @param {*} duration 显示时间，默认1.5s
 * @param {*} icon 显示图标，默认没有
 */

export function toast(title, duration = 2000, icon = "none") {
    uni.showToast({
        title,
        duration,
        icon,
    });
}

/**
 * 手机号校验
 * @param {*} mobile 手机号
 * @param {*} toast 校验不通过提示的消息内容
 * @returns
 */

export function verifyMobeil(mobile, toast = "请输入正确的手机号") {
    let regularMobile = /^1[3456789]\d{9}$/.test(mobile);
    if (mobile == "" || !regularMobile) {
        uni.showToast({
            title: toast,
            duration: 1500,
            icon: "none",
        });
        return;
    }
    return true;
}

/**
 * 密码校验
 * @param {*} password 密码(6-16位数字加字母)
 * @param {*} toast 校验不通过提示的消息内容
 * @returns
 */

export function verifyPassword(
    password,
    toast = "登录密码应为6-16位数字加字母"
) {
    let regularPassword = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(
        password
    );
    if (password == "" || !regularPassword) {
        uni.showToast({
            title: toast,
            duration: 1500,
            icon: "none",
        });
        return;
    }
    return true;
}
/**
 * 身份证校验
 * @param {*} sId
 * @returns
 */

export function isCardID(sId, toast = "你输入的身份证长度或格式错误") {
    if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
        uni.showToast({
            title: toast,
            duration: 1500,
            icon: "none",
        });
        return;
    }
    return true;
}

/**
 * 判断是否登录
 * @param {*} 
 * @returns
 */


 function isLogin() {
    return uni.getStorageSync("mobile") ? true : false
}

/**
 * 判断是否安卓
 * @param {*} 
 * @returns
 */

export function isAndroid() {
    const res = uni.getSystemInfoSync();
    return res.platform.toLocaleLowerCase() == "android"
}

/**
 * 判断是否ios
 * @param {*} 
 * @returns
 */

export function isPhoneX() {
    const res = uni.getSystemInfoSync();
    let iphonex = false;
    let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
    const model = res.model.replace(/\s/g, "").toLowerCase()
    if (models.includes(model)) {
        iphonex = true;
    }
    return iphonex;
}

/**
 * 计算当前后一个月的日期
 * @param {*} 
 * @returns
 */
export function initDate() {
    let weekArrFont = ["日", "一", "二", "三", "四", "五", "六"];
    let oneDay = 24 * 60 * 60 * 1000;
    let monthDate = [];
    let date = new Date();
    let newDate = new Date().getTime();
    for (let i = 0; i < 7; i++) {
        let year = date.getFullYear();
        let dayTime = i * oneDay + newDate; // 每天对应的时间搓
        let itemDate = new Date(dayTime); // 每天的日期对象
        let font = weekArrFont[itemDate.getDay()];
        let dateMonth =
            itemDate.getMonth() + 1 < 10
                ? "0" + (itemDate.getMonth() + 1)
                : itemDate.getMonth() + 1;
        let dateDay =
            itemDate.getDate() < 10 ? "0" + itemDate.getDate() : itemDate.getDate();
        let day = `${year}-${dateMonth}-${dateDay}`;
        let name = `${dateDay}`;
        let item = {
            name,
            font,
            day,
        };
        monthDate.push(item);
    }
    return monthDate;
}

/**
 * 日期时间计算 获取当前时间前n天的日期
 * @param {*} 
 * @returns
 */
export const getBeforeDate = (n) => {
    var n = n;
    var d = new Date();
    var year = d.getFullYear();
    var mon = d.getMonth() + 1;
    var day = d.getDate();
    if(day <= n) {
        if(mon > 1) {
            mon = mon - 1;
        } else {
            year = year - 1;
            mon = 12;
        }
    }
    d.setDate(d.getDate() - n);
    year = d.getFullYear();
    mon = d.getMonth() + 1;
    day = d.getDate();
    let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    return s;
  }

/**
 * 上传文件
 * @param {*} 
 * @returns
 */
export function uploadImage(url) {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '图片上传中',
        });
      let result = uni.uploadFile({
        url: tui.interfaceUrl()+'/image/upload', // 仅为示例，非真实的接口地址
        filePath: url,
        name: 'file',
        formData: {},
        success: (res) => {
          setTimeout(() => {
            uni.hideLoading();
            resolve(JSON.parse(res.data));
          }, 1000)
        }
      });
    })
  }
/**
 * 判断是否打开gps
 * @param {*} 
 * @returns
 */
export function openGps() {
    let system = uni.getSystemInfoSync(); // 获取系统信息
    if (system.platform === 'android') { // 判断平台
        var context = plus.android.importClass("android.content.Context");
        var locationManager = plus.android.importClass("android.location.LocationManager");
        var main = plus.android.runtimeMainActivity();
        var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
            uni.showModal({
                title: '提示',
                content: '请打开定位服务功能',
                showCancel: false, // 不显示取消按钮
                success() {
                    var Intent = plus.android.importClass('android.content.Intent');
                    var Settings = plus.android.importClass('android.provider.Settings');
                    var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    main.startActivity(intent); // 打开系统设置GPS服务页面

                }
            });
        }
    } else if (system.platform === 'ios') {
        var cllocationManger = plus.ios.import("CLLocationManager");
        var enable = cllocationManger.locationServicesEnabled();
        var status = cllocationManger.authorizationStatus();
        plus.ios.deleteObject(cllocationManger);
        console.log("手机系统的定位没有打开");
        uni.showModal({
            title: '提示',
            content: '请打开定位服务功能',
            showCancel: false, // 不显示取消按钮
            success() {
                var UIApplication = plus.ios.import("UIApplication");
                var application2 = UIApplication.sharedApplication();
                var NSURL2 = plus.ios.import("NSURL");
                var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
                application2.openURL(setting2);
                plus.ios.deleteObject(setting2);
                plus.ios.deleteObject(NSURL2);
                plus.ios.deleteObject(application2);
            }
        });
    }
}
/**
 * 获取导航栏高度(微信小程序包含胶囊高度)
 * @param {*} 
 * @returns
 */
export function getNavBarHeight() {
	// #ifdef MP-WEIXIN
	let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
	// 导航栏高度 = 胶囊高度 + 上间距 + 下间距 + 微调	（menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight'] = 上间距）	        
	let navbarHeight = menuButtonInfo.height + (menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight']) * 2 + 2
	// #endif
	// #ifdef APP-PLUS || H5
	let navbarHeight = 44
	// #endif
	return navbarHeight
}
